<template>
  <div class="dashboard-container">
    <div class="data-overview">
      <div class="data-card">
        <h3>监测点数量</h3>
        <p class="big-number">{{ topData.pointNum }}</p>
      </div>
      <div class="data-card">
        <h3>病虫害数量</h3>
        <p class="big-number">{{ topData.pestNum }} </p>
      </div>
      <div class="data-card">
        <h3>防治措施数量</h3>
        <p class="big-number">{{ topData.protectiveNum }}</p>
      </div>
      <div class="data-card">
        <h3>用户数量</h3>
        <p class="big-number">{{ topData.userNum }}</p>
      </div>
    </div>

    <div class="chart-row">
      <div class="chart-container">
        <div class="chart-title">病虫害趋势</div>
        <div ref="precipitationChart" class="chart" style="height: 300px;"></div>
      </div>
      <div class="chart-container">
        <div class="chart-title">监测点区域</div>
        <div ref="refererChart" class="chart" style="height: 300px;"></div>
      </div>
    </div>

    <div class="chart-row">
      <div class="chart-container">
        <div class="chart-title">监测点对比</div>
        <div ref="budgetChart" class="chart" style="height: 300px;"></div>
      </div>
      <div class="chart-container">
        <div class="chart-title">病虫害情况</div>
        <div ref="supportChart" class="chart" style="height: 300px;"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import  { topData, district, condition, compare, trend } from '@/api/statistics';

export default {
  name: 'Statistics',
  mounted() {
    this.initPrecipitationChart();
    this.initRefererChart();
    this.initBudgetChart();
    this.initSupportChart();
    this.getTopData();
    this.getRefererData(); // 获取监测点区域数据
    this.getSupportData(); // 获取病虫害情况数据
    this.getBudgetData(); // 获取地区对比情况数据
    this.getPrecipitationData(); //获取病虫害趋势数据
  },
  data() {
    return {
      topData: {
        pointNum: 0,
        pestNum: 0,
        protectiveNum: 0,
        userNum: 0
      },
      refererChartData: [],
      supportChartData: [],
      budgetChartData: [],
      precipitationChartData: []
    };
  },
  methods: {
    getTopData() {
      topData().then(response => {
        this.topData = response.data;
      })
      .catch(error => {
          console.error('查询数据失败', error);
          this.$message({
              message: response.message,
              type: 'error'
          });
      });
    },

    getRefererData() {
      district().then(response => {
        if (response.success) {
          this.refererChartData = response.data;
          this.initRefererChart(); // 数据加载完成后重新初始化图表
        } else {
          console.error('查询数据失败', response.message);
          this.$message({
              message: response.message,
              type: 'error'
          });
        }
      }).catch(error => {
        console.error('查询数据失败', error);
        this.$message({
            message: '获取监测点区域数据失败',
            type: 'error'
        });
      });
    },

    getSupportData() {
      condition().then(response => {
        if (response.success) {
          this.supportChartData = response.data;
          this.initSupportChart(); // 数据加载完成后重新初始化图表
        } else {
          console.error('查询数据失败', response.message);
          this.$message({
              message: response.message,
              type: 'error'
          });
        }
      }).catch(error => {
        console.error('查询数据失败', error);
        this.$message({
            message: '获取病虫害情况数据失败',
            type: 'error'
        });
      });
    },

    getBudgetData() {
      compare().then(response => {
        if (response.success) {
          this.budgetChartData = response.data;
          this.initBudgetChart(); // 数据加载完成后重新初始化图表
        } else {
          console.error('查询数据失败', response.message);
          this.$message({
              message: response.message,
              type: 'error'
          });
        }
      }).catch(error => {
        console.error('查询数据失败', error);
        this.$message({
            message: '获取病虫害情况数据失败',
            type: 'error'
        });
      });
    },

    getPrecipitationData() {
      trend().then(response => {
        if (response.success) {
          this.precipitationChartData = response.data;
          this.initPrecipitationChart(); // 数据加载完成后重新初始化图表
        } else {
          console.error('查询数据失败', response.message);
          this.$message({
              message: response.message,
              type: 'error'
          });
        }
      }).catch(error => {
        console.error('查询数据失败', error);
        this.$message({
            message: '获取病虫害情况数据失败',
            type: 'error'
        });
      });
    },
    
    initPrecipitationChart() {
      const chart = echarts.init(this.$refs.precipitationChart);

      if (!this.precipitationChartData || this.precipitationChartData.length === 0) return; // 如果数据未加载完成，直接返回

      // 获取当前日期并生成往前六天的日期数组
      const dates = this.precipitationChartData.map(item => item.date);
      const normalPointData = this.precipitationChartData.map(item => item.normalNum);
      const exceptionPointData = this.precipitationChartData.map(item => item.exceptionNum);
      const option = {
        legend: {
          data: ['病虫害监测点', '正常监测点']
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value',
          max: 8,
          axisLabel: {
            formatter: '{value}'
          }
        },
        series: [
          {
            name: '病虫害监测点',
            type: 'line',
            data: exceptionPointData,
            smooth: true
          },
          {
            name: '正常监测点',
            type: 'line',
            data: normalPointData,
            smooth: true
          }
        ]
      };
      chart.setOption(option);
    },
    initRefererChart() {
      if (!this.refererChartData || this.refererChartData.length === 0) return; // 如果数据未加载完成，直接返回
    
      const chart = echarts.init(this.$refs.refererChart);

      // 提取图例和数据
      const legendData = this.refererChartData.map(item => item.district);
      const seriesData = this.refererChartData.map(item => ({ value: item.pointCount, name: item.district }));
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: legendData
        },
        series: [
          {
            name: '监测点数量：',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: seriesData
          }
        ]
      };
      chart.setOption(option);
    },
    initBudgetChart() {
      if (!this.budgetChartData || this.budgetChartData.length === 0) return; // 如果数据未加载完成，直接返回
      const chart = echarts.init(this.$refs.budgetChart);
      
       // 提取数据
      const districts = this.budgetChartData.map(item => item.district);
      const normalPointData = this.budgetChartData.map(item => item.normalPoint);
      const exceptionPointData = this.budgetChartData.map(item => item.exceptionPoint);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['病虫害监测点', '正常监测点']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: districts
        },
        series: [
          {
            name: '病虫害监测点',
            type: 'bar',
            stack: 'total',
            label: {
              show: true
            },
            emphasis: {
              focus: 'series'
            },
            data: exceptionPointData
          },
          {
            name: '正常监测点',
            type: 'bar',
            stack: 'total',
            label: {
              show: true
            },
            emphasis: {
              focus: 'series'
            },
            data: normalPointData
          }
        ]
      };
      chart.setOption(option);
    },
    initSupportChart() {
      if (!this.supportChartData || this.supportChartData.length === 0) return; // 如果数据未加载完成，直接返回
      const chart = echarts.init(this.$refs.supportChart);
      // 提取数据
      const seriesData = this.supportChartData.map(item => ({ value: parseInt(item.num), name: item.status }));
      const option = {
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            name: '监测情况',
            type: 'pie',
            radius: '70%',
            data:seriesData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      chart.setOption(option);
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.data-overview {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.data-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  flex: 1;
  margin: 10px;
  min-width: 200px;
  text-align: center;
}

.big-number {
  font-size: 24px;
  font-weight: bold;
  margin-top: 10px;
}

.chart-row {
  display: flex;
  margin-bottom: 20px;
}

.chart-container {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin: 0 10px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.chart {
  width: 100%;
}
</style>